﻿
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using iBackupExplorer.Data;
using iBackupExplorer.Utils;

namespace iBackupExplorer.Services
{
    class InfosServices
    {
        public static async Task<Infos> getInfos(string backupPath)
        {
            Infos infos = new Infos();
            string fullpath = Path.Combine(backupPath, infos.fileName);

            if (File.Exists(fullpath))
            {
                XElement xelement = XElement.Load(fullpath);
                XElement[] Strings = (from item in xelement.Descendants("string")
                                      select item).ToArray();

                XElement[] Keys = (from item in xelement.Descendants("key")
                                      select item).ToArray();

                infos.BuildVersion = Strings[0].Value;
                infos.DeviceName = Strings[1].Value;
                infos.DisplayName = Strings[2].Value;
                
                if (Keys[7].Value == "Phone Number")
                {
                    infos.PhoneNumber = Strings[6].Value;
                    infos.ProductType = Strings[7].Value;
                    infos.iOS = Strings[8].Value;
                }
                else
                {
                    infos.ProductType = Strings[6].Value;
                    infos.iOS = Strings[7].Value;
                }

                infos.iOSVersionEnum = getiOs(infos.iOS);

                Strings = (from item in xelement.Descendants("date")
                           select item).ToArray();

                DateTime lstbackup;
                if (DateTime.TryParse(Strings[0].Value, out lstbackup))
                    infos.LastBackup = lstbackup;
            }

            return infos;
        }
        private static iOSVersion getiOs(string iOS)
        {
            switch (iOS)
            {
                case "5.1":
                case "5.1.1" :
                case "5.0.1" :
                    return iOSVersion.iOS_5;
                default :
                    return iOSVersion.iOS_6;
            }
        }
    }
}
